/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.UserTransaction;

/**
 *
 * @author Save
 */
@ManagedBean
@SessionScoped
public class ManagedBeanBenutzer {

    @PersistenceContext
    private EntityManager em;
    @Resource
    private UserTransaction utx;
    private Benutzer benutzer;
    

    public ManagedBeanBenutzer() {
    }

    public Benutzer getBenutzer() {
        if (benutzer == null) {
            String userMail = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
            if(userMail != null){
                benutzer = (Benutzer)em.createNamedQuery("Benutzer.findByEmail", Benutzer.class).setParameter("email", userMail).getSingleResult();
            }
        }
        return benutzer;
    }

    public void setBenutzer(Benutzer benutzer) {
        this.benutzer = benutzer;
    }

    public boolean istEingeloggt() {
        FacesContext fcon = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) fcon.getExternalContext().getRequest();

        if (request.getUserPrincipal() == null) {
            return false;
        }
        return true;
    }

    public boolean istAdmin() {
        FacesContext fcon = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) fcon.getExternalContext().getRequest();
        if (!request.isUserInRole("admin")) {
            return false;
        }
        return true;
    }

    public String abmelden() {
        FacesContext fcon = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) fcon.getExternalContext().getRequest();
        try {
            request.logout();
            request.getSession(false).invalidate(); 
        } catch (ServletException ex) {
        }
        return "/faces/index.xhtml";
    }
    public String change() {
       
        try {
            utx.begin();
            em.merge(benutzer);
            utx.commit();

        } catch (Exception e) {
        }
        return "/faces/kontoAktuell.xhtml";
    }
     public String cancel() {
    
        return "/faces/index.xhtml";
    }

}
